package com.faithbj.printer.service.Impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.faithbj.printer.service.RemoteInteractive;

public class RemoteInteractiveImpl implements RemoteInteractive {

	@Override
	public String getResource(String url, CloseableHttpClient httpclient) throws ClientProtocolException, IOException {
		 HttpGet httpGet = new HttpGet(url);
         CloseableHttpResponse response = httpclient.execute(httpGet);
         HttpEntity entity = response.getEntity();
         return EntityUtils.toString(entity);
	}
	
	@Override
	public String postResource(String url, Map<String, String> params,
			CloseableHttpClient httpClient) throws ClientProtocolException, IOException {
		HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList <NameValuePair>(params.size());
        for(Entry<String, String> entry : params.entrySet()){
        	nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
	}


	public String getResource_version4_1(String url, String charset,
			HttpClient hc) throws ClientProtocolException, IOException {
		HttpGet httpget = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = hc.execute(httpget, responseHandler);
		return responseBody;
	}

	@Override
	public String getResource(String url) throws ClientProtocolException,
			IOException {
		CloseableHttpClient  httpClient = HttpClients.createDefault();
		String html = this.getResource(url, httpClient);
		httpClient.close();
		return html;
	}
	
}
